/**
 * 
 */
package com.huniu.analysis.dictionary.tree.model;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.charset.Charset;

import com.huniu.utility.constant.GlobalConstants;

/**
 * @author zandy (chenheng)
 * 
 */
public class ValuePair implements Externalizable {

	private String value;
	private int weight;

	public ValuePair() {

	}

	public ValuePair(String value) {
		setValue(value);
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		if ( value != null ) {
			Charset charset = Charset.forName(GlobalConstants.CHARSET);
			byte[] array = value.getBytes(charset);
			int weight = 0;
			for (byte item : array) {
				weight += Math.abs(item);
			}
			setWeight(weight);
		}
		this.value = value;
	}

	public int getWeight() {
		return weight;
	}

	private void setWeight(int weight) {
		this.weight = weight;
	}

	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		int length = in.readInt();
		byte[] array = new byte[length];
		in.read(array);
		Charset charset = Charset.forName(GlobalConstants.CHARSET);
		String value = new String(array, charset);
		setValue(value);
	}

	public void writeExternal(ObjectOutput out) throws IOException {
		Charset charset = Charset.forName(GlobalConstants.CHARSET);
		byte[] array = value.getBytes(charset);
		out.writeInt(array.length);
		out.write(array);
	}
	
	public int hashCode() {
		return value == null ? 0 : value.hashCode() ;
	}
	
	public boolean equals(Object obj) {
		if ( this == obj ) {
			return true ;
		}
		if ( obj == null || ( obj.getClass() != this.getClass() ) ) {
			return false ;
		}
		ValuePair pair = (ValuePair) obj ;
		if ( this.value == pair.value || (this.value != null && this.value.equals( pair.value ))) {
			return true ;
		}
		return false ;
	}
}
